import { configSetParam } from "@/utils";

// 封装流式请求方法
export const streamRequestTxt = async (content: string, onDataReceived: (string) => void) => {
  const data = {
    bot_id: configSetParam.botId,
    user_id: "123456",
    stream: true,
    auto_save_history: true,
    additional_messages: [{
      role: "user",
      content: content,
      content_type: "text"
    }]
  }
  try {
    const response = await fetch('https://api.coze.cn/v3/chat', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${configSetParam.token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    // 处理非200响应
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 获取可读流和读取器
    const reader = response.body?.getReader();
    const decoder = new TextDecoder('utf-8');
    let partialData = '';
    if (!reader) return;
    // 持续读取流数据
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      // 解码并处理数据块
      const chunk = decoder.decode(value, { stream: true });
      partialData += chunk;
      // 处理可能的多个事件（按换行分割）
      const lines = partialData.split('\n');
      partialData = lines.pop() || ''; // 保留未完成的行
      for (const line of lines) {
        if (line.startsWith('conversation.message.delta')) {
          const jsonData = line.replace('', '');
          try {
            const parsed = JSON.parse(jsonData);
            if (parsed.content) {
              onDataReceived(parsed.content); // 触发回调更新UI
            }
          } catch (e) {
            console.error('JSON解析失败:', e);
          }
        }
      }
    }
  } catch (error) {
    console.error('流式请求失败:', error);
    throw error; // 向上传递错误
  }
};
// 使用防抖渲染（每秒更新不超过60次）
// let renderQueue = '';
// const debouncedUpdate = useRef(debounce(() => {
//   setMessage(prev => prev + renderQueue);
//   renderQueue = '';
// }, 16)).current;

// // 在回调中累积数据
// onDataReceived: (chunk) => {
//   renderQueue += chunk;
//   debouncedUpdate();
// }
